<template>
	<view>
		<block v-if="hasLoginFlag">
			<lib-type :isNViewFlag="false" :tabIndex.sync="tabIndex" :tabArr="tabList" @change="tabChange"></lib-type>
			<view class="swiperWrap">
				<swiper class="swiper" :current="tabIndex" :skip-hidden-item-layout="true" duration="300" @change="swiperChange" style="height:100%;">
					<swiper-item v-for="(item,index) in msgList" :key="index"> 
						<scroll-view style="height: 100%;" 
							scroll-y 
							:refresher-threshold="45"
							:refresher-enabled="true" 
							:scroll-anchoring="true"
							refresher-background="#f4f4f4"
							:refresher-triggered="refresherTriggered"
							@refresherrefresh="refresherrefresh"
							@refresherrestore="refresherrestore"
							@refresherabort="refresherabort"
							upper-threshold="50"  
							@scrolltolower="loadMore(index)"
						>
							<block v-if="item.firstload">
								<block v-if="item.isHasDataFlag">
									<block v-for="(itemInner,indexInner) in item.list" :key="indexInner">
										<view class="padd" v-if="tabList[index].typeId == 0" style="background: #fff;">
											<conversation :itemInner="itemInner" @handleRoute="handleRoute"></conversation>
										</view>
										<view class="padd" v-if="tabList[index].typeId == 1">
											<sys-notice :itemInners="itemInner" :msgIndex="indexInner" @setReadTag="setReadTag"></sys-notice>
										</view>
									</block>
									<loading-view :loading="item.loading"></loading-view>
								</block>
								<block v-else-if="item.isHasDataFlag == false">
									<no-data></no-data>
								</block>
							</block>
							<block v-else>
								
							</block>
						</scroll-view>
					</swiper-item>
				</swiper>
			</view>
		</block>
		<block v-else-if="hasLoginFlag == false">
			<view class="wholeWh">
				<image class="noLoginImg" src="../../static/images/noZxLogin.png"></image>
				<view>登录体验更多精彩</view>
				<button class="comBtn" @tap="goLogin">去登录</button>
			</view>
		</block>
		<common-alert :showAlertFlag="showAlertFlag">
			<view class="alertContent">是否标记为已读?</view>
			<view class="tui-alert-btn" :hover-stay-time="150">
				<view class="cancelBtn" @tap.stop="cancel">取消</view>
				<view class="sureBtn" @tap="sureFun">确认</view>
			</view>
		</common-alert>
	</view>
</template>

<script>
	import LibType from './components/LibType'
	import SysNotice from './components/SysNotice'
	import Conversation from './components/Conversation'
	import { getMsgList,setMsgReadTag } from '@/api/index/index'
	export default {
		components:{
			LibType,
			SysNotice,
			Conversation
		},
		data() {
			return {
				tabList:[
					{typeName:'我的私聊',typeId:0},
					{typeName:'系统通知',typeId:1},
				],
				tabIndex:0,
				typeId:0,//默认系统通知
				conversationList:[],
				msgList:[],
				hasLoginFlag:null,
				timer:null,
				triggered: false,
				refresherTriggered: false,
				_refresherTriggered: false,
				showAlertFlag:false,
				msgId:'',
				currMsgIndex:-1,
				initLoadNum:1
			}
		},
		onLoad(){
			uni.$on('changeLoginStaToLogin', this.changeLoginStaToLogin);
			uni.$on('changeLoginStaToLogout', this.changeLoginStaToLogout);
		},
		onShow(){
			if(uni.getStorageSync('token') == ''){
				this.hasLoginFlag = false;
			}else{
				this.hasLoginFlag = true;
				this.typeId = 1;
				this.tabList = this.tabList.filter(item=>{
					return item.typeId == 1
				});
				this.getList();
				// if(!getApp().globalData.isSDKReady){
				// 	if(!uni.getStorageSync('IMRefuseNum')){
				// 		this.timer = setInterval(()=>{
				// 			if(getApp().globalData.isSDKReady){
				// 				clearInterval(this.timer);
				// 				this.getList();
				// 			}
				// 		},1000);
				// 	}else{//欠费
				// 		this.typeId = 1;
				// 		this.tabList = this.tabList.filter(item=>{
				// 			return item.typeId == 1
				// 		});
				// 		this.getList();
				// 	}
				// }else{
				// 	this.getList();
				// }
			}
		},
		methods: {
			getList(){
				let arr = [];
				for (let i = 0; i < this.tabList.length; i++) {
					arr.push({
						list:[],
						page:1,
						isHasDataFlag:null,
						loading:false,
						firstload:false
					});
				}
				this.msgList = arr; 
				this.loasMsgList();
			},
			loasMsgList(){
				let currentIndex = this.tabIndex;
				if(this.typeId == 0){
					if(getApp().globalData.isSDKReady){
						wx.$TUIKit.getConversationList().then(imResponse => {
							this.setData({
								conversationList: imResponse.data.conversationList
							});
							var tmpConversationList = this.conversationList.filter(item=>{
								return item.type == 'C2C'
							})
							this.msgList[currentIndex].list = tmpConversationList
							//console.log(this.msgList)
							this.msgList[currentIndex].loading = false;
							this.msgList[currentIndex].firstload = true;
							if(this.msgList[currentIndex].list.length > 0){
								this.msgList[currentIndex].isHasDataFlag = true;
							}else{
								this.msgList[currentIndex].isHasDataFlag = false;
							}
						});
					}
				}else if(this.typeId == 1){
					this.msgList[currentIndex].loading = true;
					var field = {msgType:'',page:this.msgList[currentIndex].page,limit:this.limit };
					getMsgList(field).then(res=>{
						let arr = [];
						let list = res.data.datas;
						for (let i = 0; i < list.length; i++) {
							arr.push(list[i]);
						}
						this.msgList[currentIndex].isHasDataFlag = true;
						this.msgList[currentIndex].loading = false;
						this.msgList[currentIndex].list = this.msgList[currentIndex].page > 1 ? this.msgList[currentIndex].list.concat(arr) : arr;
						this.msgList[currentIndex].firstload = true;
						console.log(this.msgList)
					}).catch(err=>{
						//console.log(err)
						this.msgList[currentIndex].firstload = true;
						this.msgList[currentIndex].isHasDataFlag = false;
						this.msgList[currentIndex].loading = false;
					});
				}
			},
			getConversationList() {
				uni.$TUIKit.getConversationList().then(imResponse => {
					this.setData({
						conversationList: imResponse.data.conversationList
					});
					console.log("=================================")
					console.log(this.conversationList)
					console.log("=================================")
				});
			},
			tabChange(index){
				this.tabIndex = index;
				console.log(index)
				this.typeId = index;
				if(!this.msgList[index].firstload){
					this.loasMsgList();
				}
			},
			swiperChange(e) {
				let { current } = e.target;
				this.tabIndex = current;
				this.typeId = current;
				if(!this.msgList[current].firstload){
					this.loasMsgList();
				}
			},
			loadMore(index){
				this.msgList[index].page++;
				this.loasMsgList();
			},
			setReadTag(id,index,readTag){
				if(readTag == 1){
					this.msgId = id;
					this.currMsgIndex = index;
					this.showAlertFlag = true;
				}
			},
			cancel(){
				this.showAlertFlag = false;
			},
			sureFun(){
				uni.showLoading({
					title:'设置中...',
					mask:true
				})
				var field = { id:this.msgId };
				setMsgReadTag(field).then(res=>{
					this.util.showToastSuc('标记成功');
					setTimeout(()=>{
						this.showAlertFlag = false;
						this.msgList[1].list[this.currMsgIndex].readTag = 2;
					},1500)
				}).catch(err=>{
					console.log(err)
				});
			},
			refresherrefresh(){
				//console.log("自定义下拉刷新被触发");
				let _this = this;
				if (_this._refresherTriggered) {
					return;
				}
				_this._refresherTriggered = true;
				//界面下拉触发，triggered可能不是true，要设为true
				if (!_this.refresherTriggered) {
					_this.refresherTriggered = true;
				}
				this.loadStoreData();
			},
			refresherrestore(){
				//console.log("自定义下拉刷新被复位");
				let _this = this;
				_this.refresherTriggered = false;
				_this._refresherTriggered = false;
			},
			refresherabort(){
				//console.log("自定义下拉刷新被中止	");
				let _this = this;
				_this.refresherTriggered = false;
				_this._refresherTriggered = false;
			},
			loadStoreData(){
				let _this = this;
				setTimeout(() => {
					this.getList();
					_this.refresherTriggered = false;//触发onRestore，并关闭刷新图标
					_this._refresherTriggered = false;
				}, 1000)
			},
			changeLoginStaToLogin(){
				this.hasLoginFlag = true;
				console.log("=======================登录了===================")
				//uni.$off('changeLoginStaToLogin');
			},
			changeLoginStaToLogout(){
				this.hasLoginFlag = false;
				//uni.$off('changeLoginStaToLogout');
			},
			goLogin(){
				uni.navigateTo({
					url:'../login/login'
				})
			},
			handleRoute(id){
				const url = `../subIM/TUI-Chat/chat?conversationID=${id}&jumpPage=msgCen`;
				uni.navigateTo({
					url
				});
			},
			onConversationListUpdated(event) {
				//logger.log('TUI-conversation | onConversationListUpdated  |ok');
				this.setData({
					conversationList: event.data
				});
			}
		}
	}
</script>

<style lang="scss">
	@import url("/static/css/common/alert.css");
	/deep/.uni-scroll-view-refresh-inner>svg {
		fill: $pss-color-primary_1 !important;
	}
	/deep/.uni-scroll-view-refresh__spinner>circle{
		color:$pss-color-primary_1 !important;
	}
	.wholeWh{
		display: flex;
		justify-content: center;
		align-items: center; 
		flex-direction: column;
		font-size: $font-size26;
		color:$pss-text-colora;
		.noLoginImg{
			width: 306rpx;
			height: 208rpx;
			margin-bottom: 10rpx;
		}
		.comBtn{
			width: 280rpx;
			height: 70rpx;
			line-height: 70rpx;
			margin-top: 50rpx;
			border-radius: 50rpx;
			font-size: $font-size28;
		}
	}
	.swiperWrap{
		position: absolute;
		left: 0;
		right: 0;
		top: 100rpx;
		bottom: 0;
		background: $pss-bg-gray;
	}
</style>
